'use strict';
exports.main = async (event, context) => {
    const db = uniCloud.database();
    const collection = db.collection('ad_info');

    // 从请求中获取数据或使用默认值
    const data = event || {};
    
    // 获取内容和刊登天数
    const content = data.content || "";
    const publishDays = data.publishDays || 1;
    
    // 计算价格：每个字2.5元 × 字数 × 刊登天数
    const charCount = content.replace(/\s/g, '').length; // 去除空格后的字符数
    const pricePerChar = 2.5; // 每个字2.5元
    const price = Math.round(charCount * pricePerChar * publishDays * 100) / 100; // 四舍五入到两位小数
    
    // 处理发票信息
    let invoiceInfo = null;
    if (data.needInvoice === true) {
        invoiceInfo = {
            title: data.invoiceInfo?.title || "",
            taxNumber: data.invoiceInfo?.taxNumber || "",
            email: data.invoiceInfo?.email || "",
            receiverPhone: data.invoiceInfo?.receiverPhone || ""
        };
    }
    
    // 确保 publishDate 格式正确
    const publishDate = data.publishDate || formatDate(new Date());
    
    // 构造记录数据
    const adRecord = {
        category: data.category || "个人证件",
        subCategory: data.subCategory || "身份证",
        name: data.name || "张三",
        phone: data.phone || "13800138000",
        content: content,
        publishDate: publishDate,
        publishDays: publishDays,
        needInvoice: data.needInvoice || false,
        invoiceInfo: invoiceInfo,
        price: price, // 使用计算的价格
        paymentMethod: data.paymentMethod || "wechat",
        status: "pending",
        createTime: db.serverDate(), // 使用 serverDate 而不是 new Date()
        updateTime: db.serverDate(), // 使用 serverDate 而不是 new Date()
        remark: data.remark || ""
    };

    // 字段验证
    if (!/^1[3-9]\d{9}$/.test(adRecord.phone)) {
        return { code: -1, message: "手机号格式错误" };
    }
    
    if (adRecord.content.length < 10 || adRecord.content.length > 1000) {
        return { code: -1, message: "见报内容必须为10-1000个字符" };
    }
    
    if (adRecord.name.length < 2 || adRecord.name.length > 20) {
        return { code: -1, message: "姓名必须为2-20个字符" };
    }
    
    if (adRecord.needInvoice && (!adRecord.invoiceInfo.title || !adRecord.invoiceInfo.taxNumber || !adRecord.invoiceInfo.email)) {
        return { code: -1, message: "发票信息不完整" };
    }

    try {
        // 插入记录
        console.log("尝试插入记录:", JSON.stringify({
            ...adRecord,
            createTime: "使用serverDate()",
            updateTime: "使用serverDate()"
        }));
        const res = await collection.add(adRecord);
        console.log("插入成功，结果:", res);
        return {
            code: 0,
            message: "记录添加成功",
            data: res,
            calculatedPrice: price, // 返回计算的价格，方便前端显示
            charCount: charCount // 返回字符数，方便前端显示
        };
    } catch (err) {
        console.error("插入失败:", err);
        return {
            code: -1,
            message: "记录添加失败: " + err.message,
            error: err.message,
            stack: err.stack
        };
    }
};

// 格式化日期为 YYYYMMDD
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}${month}${day}`;
} 